# -*- coding: utf-8 -*-
"""
@Time : 2024/2/27 5:44 PM
@Author: imamhusan
@Des: 文件上传
"""

from fastapi import APIRouter, UploadFile, File
from core.Response import success, fail
from config import settings
from datetime import datetime
from core.AliyunOss import AliyunOss
import os
import requests

router = APIRouter(prefix='/upload')

aliyunoss = AliyunOss()


@router.post('', description='文件上传')
async def upload_file(file: UploadFile = File(...)):
    try:
        now = datetime.now()
        cur_time = now.strftime('%Y%m%d%H%M%S%f')
        folder = cur_time[:6]
        path = f'{settings.STATIC_DIR}/uploads/{folder}'

        filename = f"{cur_time}.{file.filename.split('.')[-1]}"

        if not os.path.isdir(path):
            os.mkdir(path=path, mode=0o777)

        with open(f'{path}/{filename}', 'wb') as f:
            f.write(await file.read())

            img_url = aliyunoss.put_object_from_file(f'{folder}/{filename}', f'{path}/{filename}')
            os.remove(f'{path}/{filename}')
        return img_url
        return success(data=img_url, msg='返回图片地址')
    except Exception as e:
        return str(e)


@router.post('/test', description='文件上传')
async def get_url(file: UploadFile = File(...)):
    try:
        res = await upload_file(file)

        url = "https://xfjfpro.lllq.net.cn/index.php?s=/api/answer.v8.search/run"

        payload = f"keys={res}&is_repeat=10&wxapp_id=10031&token=0cde53f8c1d424f9897fc513bf82018d"
        headers = {
            'Host': 'xfjfpro.lllq.net.cn',
            'content-type': 'application/x-www-form-urlencoded',
            'User-Agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 16_6_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148 MicroMessenger/8.0.42(0x18002a32) NetType/WIFI Language/zh_CN',
            'Referer': 'https://servicewechat.com/wx1fb751dafd0bc6c9/9/page-frame.html'
        }

        response = requests.request("POST", url, headers=headers, data=payload)

        return response.json()
    except Exception as e:
        return fail(msg=str(e))